package com.jkgl.service;

import com.jkgl.entity.UserInfoSelfEntity;
import com.jkgl.model.userinfoday.UserInfoTodayVO;
import com.jkgl.model.result.HealthSuggestion;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class HealthAdvisorService {

    // 配置阈值常量
    private static final double MIN_STEP_TARGET_RATIO = 0.5;
    private static final double MAX_STEP_TARGET_RATIO = 1.5;
    private static final double DEEP_SLEEP_THRESHOLD = 20.0;
    private static final int CRITICAL_SBP = 180;
    private static final int HIGH_SBP = 160;
    private static final int EVENING_EXERCISE_HOUR = 20;

    public List<HealthSuggestion> generateDailyAdvice(
            UserInfoTodayVO today,
            UserInfoTodayVO yesterday,
            UserInfoSelfEntity userConfig) {

        List<HealthSuggestion> suggestions = new ArrayList<>();

        // 核心分析模块
        analyzeStepData(today, yesterday, userConfig, suggestions);
        analyzeSleepQuality(today, yesterday, suggestions);
        analyzeBloodPressure(today, suggestions);
        analyzeExerciseData(today, userConfig, suggestions);
        analyzeHydration(today, userConfig, suggestions);
        analyzeExerciseDuration(today, userConfig,suggestions);

        // 按优先级排序（1-最高，3-最低）
        return suggestions.stream()
                .sorted(Comparator.comparingInt(HealthSuggestion::getPriority))
                .collect(Collectors.toList());
    }

    // region 核心分析方法
    private void analyzeStepData(UserInfoTodayVO today, UserInfoTodayVO yesterday,
                                 UserInfoSelfEntity config, List<HealthSuggestion> list) {
        try {
            Integer target = Integer.valueOf(config.getTargetStep());
            Integer todaySteps = Integer.valueOf(today.getStepNumber());

            if (target == null || todaySteps == null) return;

            // 绝对目标分析
            if (todaySteps < target * MIN_STEP_TARGET_RATIO) {
                list.add(new HealthSuggestion("运动量不足", "每日步数",
                        String.format("当前%d步（目标%d）", todaySteps, target), 1));
            } else if (todaySteps > target * MAX_STEP_TARGET_RATIO) {
                list.add(new HealthSuggestion("运动过量警告", "步数超标",
                        String.format("已走%d步（目标%d）", todaySteps, target), 2));
            }

            // 相对变化分析
            if (yesterday != null && yesterday.getStepNumber() != null) {
                int yesterdaySteps = Integer.parseInt(yesterday.getStepNumber());
                double changeRatio = (todaySteps - yesterdaySteps) / (double) yesterdaySteps;

                if (Math.abs(changeRatio) > 0.3) {
                    String trend = changeRatio > 0 ? "增加" : "减少";
                    list.add(new HealthSuggestion("步数波动", "日变化",
                            String.format("较昨日%s%.0f%%", trend, Math.abs(changeRatio)*100), 2));
                }
            }
        } catch (Exception e) {
            // 记录日志
        }
    }

    private void analyzeSleepQuality(UserInfoTodayVO today, UserInfoTodayVO yesterday,
                                     List<HealthSuggestion> list) {
        // 睡眠时长分析
        if (today.getSleepTime() != null && today.getWakeupTime() != null) {
            Duration duration = Duration.between(today.getSleepTime(), today.getWakeupTime());
            long totalHours = duration.toHours();

            if (totalHours < 6) {
                list.add(new HealthSuggestion("睡眠不足", "总时长",
                        "仅" + totalHours + "小时（建议7-9小时）", 1));
            }
        }

        // 深度睡眠分析
        if (today.getDeepSleepPercentage() != null) {
            if (today.getDeepSleepPercentage() < DEEP_SLEEP_THRESHOLD) {
                list.add(new HealthSuggestion("深睡不足", "睡眠质量",
                        String.format("当前%.1f%%（建议≥20%%）", today.getDeepSleepPercentage()), 2));
            }
        }

        // 睡眠模式变化
        if (yesterday != null && yesterday.getSleepTime() != null) {
            long deltaMinutes = Math.abs(
                    Duration.between(today.getSleepTime(), yesterday.getSleepTime()).toMinutes()
            );
            if (deltaMinutes > 90) {
                list.add(new HealthSuggestion("作息波动", "入睡时间",
                        "较昨日变化" + deltaMinutes + "分钟，注意作息规律", 2));
            }
        }
    }

    private void analyzeBloodPressure(UserInfoTodayVO today, List<HealthSuggestion> list) {
        if (today.getSbp() == null || today.getDbp() == null) return;

        // 血压分级标准
        if (today.getSbp() >= CRITICAL_SBP || today.getDbp() >= 120) {
            list.add(new HealthSuggestion("高血压危象", "紧急提醒",
                    String.format("%d/%d mmHg，请立即就医", today.getSbp(), today.getDbp()), 1));
        } else if (today.getSbp() >= HIGH_SBP) {
            list.add(new HealthSuggestion("二级高血压", "健康预警",
                    String.format("%d/%d mmHg，建议咨询医生", today.getSbp(), today.getDbp()), 1));
        }
    }

    private void analyzeExerciseData(UserInfoTodayVO today, UserInfoSelfEntity config,
                                     List<HealthSuggestion> list) {
        if (today.getSportTimeLong() == null || config.getExerciseMinutesGoal() == null) return;

        double actual = today.getSportTimeLong();
        double target = config.getExerciseMinutesGoal();

        if (actual < target * 0.7) {
            list.add(new HealthSuggestion("运动时长不足", "每日锻炼",
                    String.format("%.1f h（目标%.1f）", actual, target), 2));
        } else if (actual > target * 1.3) {
            list.add(new HealthSuggestion("运动强度过高", "恢复建议",
                    String.format("已锻炼%.1f h，注意休息", actual), 2));
        }
    }

    private void analyzeHydration(UserInfoTodayVO today, UserInfoSelfEntity config,
                                  List<HealthSuggestion> list) {
        try {
            if (today.getWaterVolume() == null || config.getWeight() == null) return;

            double consumed = Double.parseDouble(today.getWaterVolume());
            double target = Double.valueOf(config.getWeight()) * 0.035; // 35ml/kg

            if (consumed < target * 0.8) {
                list.add(new HealthSuggestion("饮水不足", "水分摄入",
                        String.format("已喝%.1fL（建议%.1fL）", consumed, target), 2));
            }
        } catch (NumberFormatException e) {
            // 处理格式异常
        }
    }

    private void analyzeExerciseDuration(
            UserInfoTodayVO today,
            UserInfoSelfEntity userConfig,
            List<HealthSuggestion> list
    ) {
        // 空值安全校验
        if (today.getSportTimeLong() == null || userConfig.getExerciseMinutesGoal() == null) {
            return;
        }

        // 单位转换：用户当日运动时长（小时） → 分钟
        double actualMinutes = today.getSportTimeLong() * 60;
        int targetMinutes = userConfig.getExerciseMinutesGoal();

        // 核心逻辑
        if (actualMinutes < targetMinutes * 0.7) {
            list.add(new HealthSuggestion("运动不足", "每日目标",
                    String.format("今日运动%.1f小时（目标%d h）", today.getSportTimeLong(), targetMinutes), 2));
        } else if (actualMinutes > targetMinutes * 1.3) {
            list.add(new HealthSuggestion("运动过量", "恢复建议",
                    String.format("已运动%.1f小时（目标%d h）", today.getSportTimeLong(), targetMinutes), 2));
        }
    }
    // endregion
}